package org.jeecg.modules.villageCadreAssist.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.util.ChineseCharacterUtil;
import org.jeecg.modules.villageCadreAssist.entity.VcaFamily;
import org.jeecg.modules.villageCadreAssist.entity.VcaResident;
import org.jeecg.modules.villageCadreAssist.mapper.VcaFamilyMapper;
import org.jeecg.modules.villageCadreAssist.mapper.VcaResidentMapper;
import org.jeecg.modules.villageCadreAssist.service.IVcaFamilyService;
import org.jeecg.modules.villageCadreAssist.service.IVcaResidentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: vca_resident
 * @Author: jeecg-boot
 * @Date:   2022-02-13
 * @Version: V1.0
 */
@Service
public class VcaResidentServiceImpl extends ServiceImpl<VcaResidentMapper, VcaResident> implements IVcaResidentService {

    @Autowired
    private VcaFamilyMapper familyMapper;
    @Autowired
    private IVcaFamilyService familyService;
    @Autowired
    private SysDepartMapper departMapper;


    public IPage<VcaResident> queryPageList(Page<VcaResident> page, QueryWrapper queryWrapper, String orgCode){
        return baseMapper.queryPageList(page, queryWrapper,orgCode);
    }

    @Override
    public List<VcaResident> queryTopN(VcaResident resident, String orgCode) {
        return baseMapper.queryTopN(resident,orgCode);
    }

    @Override
    public List<Map<String, String>> queryVillageCadreList(Set<String> idcardSet, String orgCode) {
        return baseMapper.queryVillageCadreList(idcardSet,orgCode);
    }


    @Override
    @Transactional
    public void batchSave(List<VcaResident> residentList) {
        //查询用户下的组级别数据
        LoginUser user = (LoginUser)SecurityUtils.getSubject().getPrincipal();
//        Assert.isTrue(user.getOrgCode().length()==10,"只有村干才有权限导入本村数据！");

        List<SysDepart> groupList =departMapper.selectGroupList(user.getOrgCode());
        Assert.isFalse(groupList==null || groupList.size()==0,"当前用户下无组数据！");

        Map<String, SysDepart> nameCodeMap = groupList.stream()
                .filter(item->item.getDepartFullName()!=null)
                .collect(Collectors.toMap(
                        item->item.getDepartFullName().replace(":",""),
                        item->item));
        Date now = new Date();

        Map<String, List<VcaResident>> familyMap = residentList.stream().collect(Collectors.groupingBy(VcaResident::getFamilyCode));
        Set<String> familyCodeSet = familyMap.keySet();
        //删除已存在的，然后重新构建这些family。不存在此次导入的户口，不做处理
        familyMapper.deleteBatchByFamilyCodes(familyCodeSet);
        List<VcaFamily> familyList = new ArrayList<>();
        for (String familyCode : familyCodeSet) {
            List<VcaResident> vcaResidents = familyMap.get(familyCode);
            SysDepart depart = nameCodeMap.get(vcaResidents.get(0).getHostAddress());

            vcaResidents.forEach(item->{
                item.setOrgCode(depart.getOrgCode());
            });
            if(depart !=null && StringUtils.isNotEmpty(depart.getOrgCode())){
                VcaFamily family = new VcaFamily();
                family.setFamilyCode(familyCode);
                family.setFamilyNum(vcaResidents.size());
                family.setAreaCode(depart.getOrgCode());
                family.setCreateBy(user.getUsername());
                family.setCreateTime(now);
                familyList.add(family);
            }else{//移除不在地区权限的数据
                residentList.removeAll(vcaResidents);
            }
        }
        familyService.saveBatch(familyList);

        residentList.stream().forEach(item->{
            SysDepart depart = nameCodeMap.get(item.getHostAddress());
            String idcard = item.getIdcard();
            item.setBirthday(Integer.valueOf(idcard.substring(6,14)));
            item.setSex(Integer.valueOf(idcard.substring(16,17))%2);
            item.setFirstLetter(ChineseCharacterUtil.getSpells(item.getResidentName()));
            item.setHostAddress(depart.getDepartFullName());//需要xxx镇:xxx村:xxx组格式的
            item.setCreateBy(user.getUsername());
            item.setCreateTime(now);
        });
        //对于已存在的居民做更新，不存在的插入
        //1、创建并插入到临时表，引入临时表为了提高效率
        this.baseMapper.createTempTable();
        this.baseMapper.addTemp(residentList);
        //2、不在本次导入的总数据中的
        this.baseMapper.compareAndSetNotLocal(user.getOrgCode());
        //3、更新已存在的数据
        this.baseMapper.compareAndUpdate(user.getOrgCode());
        //4、添加不存在的数据
        this.baseMapper.compareAndInsert(user.getOrgCode());
        //5、清空数据
        this.baseMapper.clearTempTable(user.getOrgCode());
    }



}
